import React from 'react'
import { connect } from 'dva'

import AddressItem from '../components/AddressItem'
import Title from '../components/Title'

class Index extends React.Component {
    toEdit = () => {
        const { history } = this.props
        history.push('/addressEdit')
    }

    componentDidMount() {
        const { dispatch } = this.props
        dispatch({
            type: 'user/findAddress'
        })
    }
    chooseAddress = (address) => {
        console.log(address)
        const { dispatch, history, order } = this.props
        let newOrder = {
            ...order.order,
            address: address
        }
        dispatch({
            type: 'order/setOrder',
            payload: newOrder
        })
        history.go(-1)
    }
    renderAddressList = () => {
        const { user } = this.props
        const { list } = user.addressList

        return list.map(item => (
            <AddressItem
                data={item}
                key={item._id}
                hideBtn
                chooseAddress={this.chooseAddress}
            />
        ))
    }

    render() {
        return (
            <div className='addressList'>
                <Title title="我的地址" />
                {this.renderAddressList()}
            </div>
        )
    }
}

const mapState = state => ({
    user: state.user,
    order: state.order
})
export default connect(mapState)(Index)
